<template>
  <div class="log-container">
    <el-card class="log-card">
      <template #header>
        <div class="card-header">
          <span>日志管理</span>
          <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0" v-if="userRole !== 'USER'">批量删除</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operationType" placeholder="请选择操作类型" clearable class="operation-type-select">
            <el-option label="全部" value="" />
            <el-option label="新增" value="新增" />
            <el-option label="修改" value="修改" />
            <el-option label="删除" value="删除" />
            <el-option label="查询" value="查询" />
            <el-option label="登录" value="登录" />
            <el-option label="登出" value="登出" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作模块">
          <el-input v-model="searchForm.operationModule" placeholder="请输入操作模块" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 - 新版表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :row-class-name="tableRowClassName"
        table-layout="auto"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column label="编号" width="60" align="center">
          <template #default="{ $index }">
            {{ (currentPage - 1) * pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="操作人员" min-width="80" align="center" show-overflow-tooltip />
        <el-table-column prop="operationModule" label="系统模块" min-width="100" align="center" show-overflow-tooltip />
        <el-table-column prop="operationType" label="操作类型" min-width="90" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag 
              :type="getTagType(row.operationType)" 
              effect="light" 
              size="small"
            >
              {{ row.operationType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ipAddress" label="操作IP" min-width="110" align="center" show-overflow-tooltip />
        <el-table-column prop="requestMethod" label="请求方法" min-width="90" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag 
              :type="getMethodTagType(row.requestMethod)" 
              size="small"
            >
              {{ row.requestMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="requestUri" label="请求URI" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column prop="operationTime" label="操作时间" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-button type="danger" link @click="handleDelete(row)" v-if="userRole !== 'USER'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="日志详情" width="800px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">{{ detailLog.id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailLog.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ detailLog.username }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{ detailLog.operationType }}</el-descriptions-item>
        <el-descriptions-item label="操作模块">{{ detailLog.operationModule }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ detailLog.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="请求方法">{{ detailLog.requestMethod }}</el-descriptions-item>
        <el-descriptions-item label="请求URI">{{ detailLog.requestUri }}</el-descriptions-item>
        <el-descriptions-item label="请求参数">
          <pre>{{ detailLog.requestParams }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ detailLog.operationTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOperationLogsByPage, deleteOperationLog, batchDeleteOperationLogs } from '@/api/operationLog'

// 获取当前用户角色
const userRole = computed(() => {
  const userStr = localStorage.getItem('user')
  if (userStr) {
    try {
      const userData = JSON.parse(userStr)
      return userData.role || ''
    } catch (e) {
      console.error('解析用户数据失败:', e)
      return ''
    }
  }
  return ''
})

// 搜索表单
const searchForm = reactive({
  username: '',
  operationType: '',
  operationModule: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedIds = ref([])

// 获取操作日志列表
const fetchLogList = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.username,
      operationType: searchForm.operationType,
      operationModule: searchForm.operationModule
    }
    const res = await getOperationLogsByPage(params)
    if (res.success) {
      tableData.value = res.data.list
      total.value = res.data.total
    } else if (!res._showError) {
      // 只有在拦截器没有显示错误时才显示
      ElMessage.error(res.msg || '获取操作日志列表失败')
    }
  } catch (error) {
    console.error('获取操作日志列表失败：', error)
    // 只有在拦截器没有显示错误时才显示
    if (!error._showError) {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '获取操作日志列表失败')
      } else {
        ElMessage.error('获取操作日志列表失败，请稍后重试')
      }
    }
  } finally {
    loading.value = false
  }
}

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 页码大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  // 切换每页条数后，如果当前页码超出范围，重置为第一页
  if (currentPage.value > Math.ceil(total.value / size)) {
    currentPage.value = 1
  }
  fetchLogList()
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchLogList()
}

// 表格多选
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 表格行样式
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? '' : 'row-stripe'
}

// 操作类型标签颜色
const getTagType = (type) => {
  const typeMap = {
    '新增': 'success',
    '修改': 'warning',
    '删除': 'danger',
    '查询': 'info',
    '登录': 'primary',
    '登出': ''
  }
  return typeMap[type] || 'info'
}

// 请求方法标签颜色
const getMethodTagType = (method) => {
  const methodMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger'
  }
  return methodMap[method] || 'info'
}

// 详情对话框
const detailDialogVisible = ref(false)
const detailLog = ref({})

// 查看日志详情
const handleDetail = (row) => {
  detailLog.value = { ...row }
  detailDialogVisible.value = true
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchLogList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.username = ''
  searchForm.operationType = ''
  searchForm.operationModule = ''
  currentPage.value = 1
  handleSearch()
}

// 删除操作日志
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该操作日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteOperationLog(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      fetchLogList()
    } else if (!res._showError) {
      // 只有在拦截器没有显示错误时才显示
      ElMessage.error(res.msg || '删除操作日志失败')
    }
  } catch (error) {
    if (error !== 'cancel' && !error._showError) {
      console.error('删除操作日志失败：', error)
      // 只有在拦截器没有显示错误时才显示
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '删除操作日志失败')
      } else {
        ElMessage.error('删除操作日志失败，请稍后重试')
      }
    }
  }
}

// 批量删除操作日志
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条操作日志吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await batchDeleteOperationLogs(selectedIds.value)
    if (res.success) {
      ElMessage.success('批量删除成功')
      fetchLogList()
    } else if (!res._showError) {
      // 只有在拦截器没有显示错误时才显示
      ElMessage.error(res.msg || '批量删除操作日志失败')
    }
  } catch (error) {
    if (error !== 'cancel' && !error._showError) {
      console.error('批量删除操作日志失败：', error)
      // 只有在拦截器没有显示错误时才显示
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '批量删除操作日志失败')
      } else {
        ElMessage.error('批量删除操作日志失败，请稍后重试')
      }
    }
  }
}

// 初始化
onMounted(() => {
  fetchLogList()
})
</script>

<style scoped>
.log-container {
  width: 100%;
  overflow: hidden;
  display: flex;
}

.log-card {
  flex: 1;
  margin: 0;
  padding: 0;
  height: 100%;
  border-radius: 0;
  box-shadow: none;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 15px;
}

.operation-type-select {
  width: 220px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 15px 20px;
  box-sizing: border-box;
  width: 100%;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
  width: 100% !important;
}

:deep(.el-table__inner-wrapper) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.row-stripe {
  background-color: #fafafa;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style> 